<template>
  <el-card>
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input :placeholder="$t('table.placeholder')" clearable v-model="queryForm.query"></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initGetUsersList">{{$t('table.search')}}</el-button>
      <el-button type="primary">{{$t('table.adduser')}}</el-button>
    </el-row>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column
      :prop="item.prop"
      :label="$t(`table.${item.label}`)"
      :width="item.width"
      v-for="(item,index) in options"
      :key="index">
      <template v-slot="{row}" v-if="item.prop === 'mg_state'">
        <el-switch v-model="row.mg_state" @change="changeState(row)"/>
      </template>
      <template v-slot="{row}" v-else-if="item.prop === 'create_time'">
        {{$filters.formatTime(row.create_time)}}
      </template>
      <template #default v-else-if="item.prop === 'action'">
        <el-button type="primary" size="small" :icon="Edit"></el-button>
        <el-button type="success" size="small" :icon="Setting"></el-button>
        <el-button type="danger" size="small" :icon="Delete"></el-button>
      </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="queryForm.pagenum"
      :page-sizes="[5, 10, 20, 40]"
      :page-size="queryForm.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import { Search, Edit, Setting, Delete } from '@element-plus/icons-vue'
import { getUserList, changeUserState } from '../../api/user'
import { options } from './options'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
const i18n = useI18n()
const queryForm = ref({
  query: '',
  pagenum: 1,
  pagesize: 5
})
const total = ref(0)
const tableData = ref([])

const initGetUsersList = async () => {
  const res = await getUserList(queryForm.value)
  tableData.value = res.users
  total.value = res.total
}

initGetUsersList()

// 每页展示的行数发生变化
const handleSizeChange = (value) => {
  queryForm.value.pagesize = value
  queryForm.value.pagenum = 1
  initGetUsersList()
}

// 当前页码发生变化
const handleCurrentChange = (value) => {
 queryForm.value.pagenum = value
 initGetUsersList()
}

// 修改用户状态
const changeState = async (userInfo) => {
  await changeUserState(userInfo.id, userInfo.mg_state)
  ElMessage({
    message: i18n.t('message.changeUserStateSuccess'),
    type: 'success'
  })
  initGetUsersList()
}
</script>

<style lang="scss" scoped>
.header{
  padding-bottom: 16px;
  box-sizing: border-box;
}

::v-deep{
  .el-input__suffix{
    // 处理前缀图标不垂直居中的问题
    align-items: center;
  }
}
</style>
